const express = require('express');
const router = express.Router();

const NavModel = require('../../model/navModel');
const tools = require('../../model/tools')

router.get('/', async (req, res)=>{
  let list = await NavModel.find({});
  res.render('admin/nav/index.html', {
    list
  })
});

router.get('/add', async (req, res)=>{
  res.render('admin/nav/add.html');
});

router.post('/doAdd', async (req, res)=>{
  try {
    let title = req.body.title;
    let link = req.body.link;
    let position = req.body.position;
    let is_opennew = req.body.is_opennew;
    let sort = req.body.sort;
    let status = req.body.status;
    let result = new NavModel({
      title,
      link,
      position,
      is_opennew,
      sort,
      status,
      add_time: tools.getUnix()
    });
    await result.save();
    res.render('admin/public/success.html', {
      message: '增加导航成功',
      redirectUrl: `/${req.app.locals.adminPath}/nav`
    });
  } catch (error) {
    res.render('admin/public/error.html', {
      message: '增加导航失败',
      redirectUrl: `/${req.app.locals.adminPath}/nav/add`
    });
  }
});

router.get('/edit', async (req, res)=>{
  let id = req.query.id;
  let result = await NavModel.find({_id: id});
  console.log(result);
  if(result.length > 0){
    res.render('admin/nav/edit.html', {
      list: result[0]
    })
  }else{
    res.redirect(`/${req.app.locals.adminPath}/nav`);
  }
});

router.post('/doEdit', async (req, res)=>{
  try {
    let result = await NavModel.updateOne({_id: req.body.id}, req.body);
    res.render('admin/public/success.html', {
      message: '修改导航成功',
      redirectUrl: `/${req.app.locals.adminPath}/nav`
    });
  } catch (error) {
    res.render('admin/public/error.html', {
      message: '修改导航失败',
      redirectUrl: `/${req.app.locals.adminPath}/nav/edit?id=${req.body.id}`
    });
  }
})

router.get('/delete', async (req, res)=>{
  await NavModel.deleteOne({_id: req.query.id});
  res.render('admin/public/success.html', {
    message: '删除导航成功',
    redirectUrl: `/${req.app.locals.adminPath}/nav`
  });
})

module.exports = router;